﻿using JESAI.ClamAV.NetScannerCore.Command;
using JESAI.ClamAV.NetScannerCore.Exceptions;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.ClamAV.NetScannerCore.TcpClients.Builder
{
    public class SingletonScannerTcpClientBuilder : IScannerTcpClientBuilder
    {
        public string Host { get; private set; }
        private static IScannerTCPClient ScannerTCPClientInstance;
        private static object lockObj;
        private static IScannerTCPClient Instance
        {
            get
            {
                if (ScannerTCPClientInstance == null)
                {
                    lock (lockObj)
                    {
                        if (ScannerTCPClientInstance == null)
                        {
                            ScannerTCPClientInstance = new ScannerTCPClient();
                        }
                        return ScannerTCPClientInstance;
                    }
                }
                return ScannerTCPClientInstance;
            }
        }
        public int Port { get; private set; }
        public IScannerTCPClient SocketClient { get; private set; }
       
        public IScannerTCPClient Build()
        {
            this.SocketClient = SingletonScannerTcpClientBuilder.Instance;
            Connect();
            return SocketClient;
        }
        public async Task<IScannerTCPClient> BuildAsync()
        {
            this.SocketClient = SingletonScannerTcpClientBuilder.Instance;
            await ConnectAsync();
            return SocketClient;
        }

        private async Task ConnectAsync()
        {
            try
            {
                 if (!this.SocketClient.Connected)
                await this.SocketClient.ConnectAsync(this.Host, this.Port);
            }
            catch(Exception ex)
            {
                throw new TCPServerException(this.Host, this.Port,ex);
            }

        }
        private void Connect()
        {
            try
            {
                if (!this.SocketClient.Connected)
                this.SocketClient.Connect(this.Host, this.Port);
            }
            catch (Exception ex)
            {
                throw new TCPServerException(this.Host, this.Port,ex);
            }
        }
        public void Close()
        {
            if (this.SocketClient != null&&this.SocketClient.Connected)
            {
                this.SocketClient.Close();
            }
        }
    }
}
